package com.example.demo.poc.executor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WildCardUtils {

    private static final String BRACE_REGEX_FAR = "\\$\\{(.*)\\}";
    private static final String BRACE_REGEX_NEAR = "\\$\\{(.*?)\\}";
    private static final String BRACE_START = "${";
    private static final String BRACE_END = "}";


    public static void main(String[] args) {
        getBraceInnerLongestString("${abc}9}");
    }

    public static List<String> getBraceInnerLongestString(String source) {
        List<String> subUtil = getRegexResult(source, BRACE_REGEX_FAR);
        System.out.println(subUtil.get(0));
//        for (String s : subUtil) {
//            if (changeValueMap.containsKey(s) && null != changeValueMap.get(s)) {
//                source = source.replace(startStr + s + endStr, map.get(s).toString());
//            }
//        }
        return subUtil;
    }

    public static List<String> getBraceInnerShortestString(String source) {
        List<String> subUtil = getRegexResult(source, BRACE_REGEX_NEAR);
        return subUtil;
    }


    public static String changeBraceInnerLongestValue(String source,Map<String,Object> changeValueMap){
        return changeBraceInnerValue(source,changeValueMap,true);
    }


    private static String changeBraceInnerValue(String source,Map<String,Object> changeValueMap,Boolean isLongest){
        String reg = BRACE_REGEX_FAR;
        if(!isLongest){
            reg = BRACE_REGEX_NEAR;
        }
        List<String> subUtil = getRegexResult(source, reg);
        for (String s : subUtil) {
            if (changeValueMap.containsKey(s) && null != changeValueMap.get(s)) {
                source = source.replaceAll(BRACE_START + s + BRACE_END, changeValueMap.get(s).toString());
            }
        }
        return source;
    }

    /**
     * 组装信息
     *
     * @param soap     原始信息
     * @param regex    条件 占位符
     * @param startStr 删除掉的内容
     * @param endStr   删除掉的内容
     * @param map      根据原始信息占位符中的内容作为key,获取替换进占位符中的内容
     * @return
     */
    public static String getMes(String soap, String regex, String startStr, String endStr, Map<String, Object> map) {
        List<String> subUtil = getRegexResult(soap, regex);
        for (String s : subUtil) {
            if (map.containsKey(s) && null != map.get(s)) {
                soap = soap.replace(startStr + s + endStr, map.get(s).toString());
            }
        }
        return soap;
    }

    private static List<String> getRegexResult(String source, String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(source);
        List<String> list = new ArrayList<>();
        int i = 1;
        while (matcher.find()) {
            list.add(matcher.group(i));
        }
        return list;
    }

}
